package cn.zust.ly.controller.base;

import cn.zust.ly.dto.SessionInfo;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;

/**
 * Title: 蓝拓易<br>
 * Description: 文件上传<br>
 * Copyright: Copyright (c) 2009<br>
 * Company: DCS<br>
 * 
 * @author alsa
 * @version 1.0
 */
@Controller
public class CommonUpload {

	/** 允许上传文件的类型 */
	public static final String[] ALLOWEDTYPES = new String[] { "jpg", "png",
			"gif", "bmp", "txt", "doc", "docx", "xls", "xlsx", "pdf" };

	/**
	 * 上传文件　并返回文件名，　多个文件　其文件名以“#”隔开 文件名保存格式：登陆名_时间戳.postfix
	 * 
	 * @param request
	 *            包含文件域的客户端请求
	 * @param moduleName
	 *            文件保存目录路径： 1、所有上传文件的根为webapp下的uploadFile
	 *            2、机构和企业会员的的放在orgnization子目录下 3、员工的放在member子目录下
	 *            4、质检报告放在report子目录下 5、用户上传的报告放在
	 * @param limitSize
	 *            文件大小限制
	 * @return
	 */
	public static String upload(HttpSession session, HttpServletRequest request, String moduleName,
								int limitSize) {

		String fileNames = "";
		/** 　保存路径，这个是大的临时文件路径，请根据需要放置到自己的私有文件夹中 */
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(4096);
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置文件体积的最大值
		upload.setSizeMax(limitSize);
		// 取出所有上传的文件
		@SuppressWarnings("unchecked")
		List<FileItem> fileItems = null;
		try {
			fileItems = upload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
//		// 文件名
//		String prefix = "null";
//		SessionInfo sessionInfo = (SessionInfo) session
//				.getAttribute("sessionInfo");
//		if (sessionInfo != null) {
//
//			prefix = sessionInfo.getUserId()+"";
//			System.out.println("---------" + prefix);
////			prefix = sessionInfo.getOrganizationId().toString();
//		}
//		prefix += "_";
		String name = "";
		// 文件后缀
		String postfix = "";
		// 开始循环，取出所有文件
		for (FileItem item : fileItems) {
			if (!item.isFormField()) {
				// 获取文件名
				name = item.getName();
				// 获取文件后缀
				boolean isP = false;
				postfix = name.substring(name.lastIndexOf(".") + 1,
						name.length());
				for (int i = 0; i < ALLOWEDTYPES.length; i++) {
					if (ALLOWEDTYPES[i].equals(postfix)) {
						isP = true;
						break;
					} else {
						if (i == ALLOWEDTYPES.length - 1) {
							isP = false;
						} else {
							continue;
						}
					}
				}
				if (!isP) {
					return "error";
				}

				// 文件以日期形式命名新文件名　+　文件后缀名
//				name = prefix + System.currentTimeMillis() + "." + postfix;
				name = System.currentTimeMillis() + "." + postfix;
				// 输出文件
				// fileNames +=UploadPathUtil.virtualRoot+"/"+moduleName+"/"+
				// name + "#";
				// 斜杠反过来
				fileNames += "uploadFile/" + moduleName
						+ "/" + name + "#";
				String savePath = request.getSession().getServletContext().getRealPath("/") + "/"
						+ "uploadFile/" + moduleName + "/";
				File file = new File(savePath + "/" + name);
				file.getParentFile().mkdirs();
				try {
					item.write(file);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		if (fileNames.contains("#")) {
			fileNames = fileNames.substring(0, fileNames.length() - 1);
		}
		return fileNames;
	}

	public static void main(String[] args) {

	}

}
